# -*- coding: utf-8 -*-
import sys
import time

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
import json
from common.helper import Helper
from threading import Thread
import aiohttp
import asyncio


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "旅行健康保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 保障天数
            "days": ["7d"],
            # 保障人数
            "people_count": [str(i) for i in range(1, 21)],
            # 意外身故/伤害
            "accident_death": ["100000", "150000", "200000", "250000", "300000"],
            # 意外医疗
            "accident_medical": ["10000", "20000", "30000", "40000", "50000"],
            # 急性病身故
            "acute_death": ["10000", "20000", "30000", "40000", "50000"],
            # 飞机意外
            "airplane_death": ["0", "400000"],
        }
        for v in product(plan["days"], plan["people_count"], plan["accident_death"], plan["accident_medical"],
                         plan["acute_death"], plan["airplane_death"]):

            if v[5] == "0":
                train_death = "0"
                ship_death = "0"
                bus_death = "0"
            else:
                train_death = "200000"
                ship_death = "200000"
                bus_death = "200000"
            data = Helper.formatProductInfo(plan, v)
            data["train_death"] = train_death
            data["ship_death"] = ship_death
            data["bus_death"] = bus_death
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        data = {"planClass": 2, "amountFormList": [
            {"suddennessDie": 300000, "medical": 50000, "acuteDiseaseDie": 50000, "highriskSuddennessDie": 0,
             "planeSuddennessDie": 400000, "trainSuddennessDie": 200000, "carSuddennessDie": 200000,
             "suddennessHospitalAllowance": 0, "travelRescuse": 0, "rescuse": 0},
            {"suddennessDie": 100000, "medical": 50000, "acuteDiseaseDie": 50000, "highriskSuddennessDie": 0,
             "planeSuddennessDie": 0, "trainSuddennessDie": 0, "carSuddennessDie": 0, "suddennessHospitalAllowance": 0,
             "travelRescuse": 0, "rescuse": 0},
            {"suddennessDie": dt["accident_death"], "medical": dt["accident_medical"],
             "acuteDiseaseDie": dt["acute_death"],
             "planeSuddennessDie": "0" if dt["airplane_death"] == "0" else "400000",
             "trainSuddennessDie": "200000" if dt["airplane_death"] != "0" else "0",
             "carSuddennessDie": "200000" if dt["airplane_death"] != "0" else "0"}],
                "insurantNumber": dt["people_count"],
                "beginDate": "2020-04-24", "endDate": "2020-04-30", "periodUnit": "1", "applyDays": "7"}

        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "toaUserPremium" in r.text:

            price = r.json()["quoteResult3"]["toaUserPremium"]

            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格信息更新失败:%d*/" % dt["id"])\

if __name__ == '__main__':
    s = Spider()
    Helper.runProcess( mysql=s.mysql,name=s.name,func=s.requestJson)